是否可以(或根本相关)导出静态库的成员函数?当我“dumpbin /EXPORTS”我的 .lib 文件时,我没有看到任何我定义的类成员。
链接到此 lib 文件成功,但我使用的外部工具无法读取非导出符号。
还尝试添加 .def 文件,但没有结果。
我正在尝试使用 C++ 实现动态数组。但是,我的resize()功能似乎无法正常工作。没有错误或警告。我做了一些研究并尝试查看互联网上找到的其他实现,但无法解决该问题。我把我的代码放在下面。
#include <iostream>
class Array
{
private:
int* arr;
int size = 0;
int capacity = 1;
public:
Array() { arr = new int[capacity]; }
Array(int capacity)
:
capacity(capacity)
{
arr = new int[capacity];
}
int length() const { return size; }
bool is_empty() const { return (length() == 0); }
int get(int index) const { return arr[index]; }
void set(int index, int value) { arr[index] = value; }
void resize()
{
capacity *= 2;
int* …Run Code Online (Sandbox Code Playgroud) c++ class definition member-functions dynamic-memory-allocation
当您要创建类的新 const 实例时,是否需要定义 const 函数?
不知何故,当我尝试从 const 类实例访问它们时,我的编译器找不到“常规”(不是 const)函数。
代码
#include <iostream>
class A
{
public:
mutable int x;
mutable int y;
A(int k1 = 0, int k2 = 0) :x(k1), y(k2) {}
void display()
{
std::cout << x << "," << y << "\n";
}
};
int main()
{
const A a1;
a1.x = 3;
a1.y = 8;
a1.display();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出
Error: 'this' argument to member function 'display'
has type 'const A', but function is not marked const
Run Code Online (Sandbox Code Playgroud)
我只是A::display()通过const限定对象调用成员函数a1。那么为什么 line …
我有一个成员函数需要访问成员数据和“本地”数据:
struct S final
{
int i = 123;
// ... a bunch of legacy code ...
void f()
{
// ... a bunch of legacy code ...
double d = 1.23;
// ... a bunch of legacy code ...
g(d);
// ... a bunch of legacy code ...
}
// ... a bunch of legacy code ...
void g(double& d)
{
i = 456; d = 4.56;
}
};
Run Code Online (Sandbox Code Playgroud)
这当然是有效的......但是,随着更多本地变量被f()传递到g(). 有没有一种“简单”的方法可以避免这种情况?
使用 lambda 是“常规”答案,但这意味着 的代码 …
我知道指定成员函数“const”允许我们从 const 对象调用它,但为什么我们必须在成员函数旁边显式写“const”?为什么编译器不能弄清楚
int getFoo() {
return m_foo;
}
Run Code Online (Sandbox Code Playgroud)
确实是“const”吗?
我无法弄清楚,为什么C ++不允许根据返回类型进行重载,因为在以下情况下,三个member(getter)函数具有不同的函数签名,即使在存储指向成员函数的指针时,我们也需要不同的mem-函数指针类型如下:
for instance T = std::string
using constRefPtr = const std::string&(MyStruct::*)() const;
using constValuePtr = const std::string(MyStruct::*)() const;
using valuePtr = std::string(MyStruct::*)() const;
Run Code Online (Sandbox Code Playgroud)
我已经阅读过这篇类似的文章,建议使用const和非成本成员函数。
问题:如何在不删除const每个成员函数的本质的情况下使以下(getter)重载工作(如果可以通过标准C ++实现)?
我正在使用C ++ 17。
#include <iostream>
#include <string>
template<typename T> class MyStruct
{
T m_val;
public:
explicit MyStruct(const T& value)
: m_val(value)
{}
const T& getVal() const { return m_val; } // get val as const ref(no copy of member)
const T getVal() const { return m_val; } // get …Run Code Online (Sandbox Code Playgroud) c++ ×7
class ×3
constants ×2
c++17 ×1
definition ×1
function ×1
lambda ×1
linker ×1
mutable ×1
overloading ×1