如何使用unique_ptr访问C++中的类成员和类变量
How to use unique_ptr to access class members and class variables in C++
>我有一个头文件,其中我定义了一个类,并且还使用了一个unique_ptr来访问类成员。
但是我不知道如何从克隆访问它.cpp通常,我们要做的是创建一个类的对象例如:
A obj;
bool res = obj.concate("hello");
我们如何使用unique_ptr做到这一点?
当我尝试做
bool result = access->concate("hello");
我收到以下错误:
Undefined symbols for architecture x86_64: "obja()", referenced from: _main in classA.o ld: symbol(s) not found for architecture x86_64
clone.h
--------
std::unique_ptr<class A> obja();
class A
{
public:
bool concate(string str){
string a = "hello";
return a == str;
}
private:
string b = "world";
};
clone.cpp
________
int main(){
auto access = obja();
return 0;
}
你不需要类 std::unique_ptr<class A> obja();
,括号也一样。
不确定您要在这里实现什么:auto access = obja();
我假设您试图在那里调用简洁,那么一切都可以像这样:
class A
{
public:
bool concate(string str) {
string a = "hello";
return a == str;
}
private:
string b = "world";
};
std::unique_ptr<A> obja;
int main() {
auto access = obja->concate("test");
return 0;
}
class A
{
public:
bool concate(string str) { string a = "hello"; return a == str; }
private: string b = "world";
};
std::unique_ptr<A> obja = std::make_unique <A>;
int main() {
auto access = obja->concate("test"); return 0;
}
你只是忘记分配内存。 :)
相关文章:
- 为什么在C++中首先初始化成员类
- 我正在尝试获取类私有成员中变量的输入
- 模板类变量作为非模板类的成员
- 从静态成员函数访问私有非静态类变量 - C++
- 无法使用子类变量访问超类公共成员
- 如何从doxygen输出中排除类的无证件成员函数/变量
- 从成员变量更新类变量或调用类功能是给出运行时错误
- 如何使用unique_ptr访问C++中的类成员和类变量
- 如何通过其他.cpp文件中的类变量编辑公共成员变量
- 对成员类/对象变量使用指针更好吗
- 返回类成员引用变量会导致运行时错误
- 将pthread_mutex_t和pthread_cond_t作为类成员静态变量的任何缺点
- 声明为类变量的对象没有可用的成员
- 继承类的成员函数不会更改继承的基类变量
- 作为类成员的 C++ 类变量
- 类成员引用变量是否有内置"const-correctness"?
- 如何在继承类中创建父类变量数组作为私有成员
- 一个函数可以访问的类变量或成员函数中仍然是对象感知的静态变量
- 是在第一次调用静态成员函数之前初始化的静态类变量
- C++将成员变量传递给成员类