如何使用unique_ptr访问C++中的类成员和类变量

How to use unique_ptr to access class members and class variables in C++

本文关键字:成员 类变量 C++ unique 何使用 ptr 访问      更新时间:2023-10-16

>我有一个头文件,其中我定义了一个类,并且还使用了一个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;
 }

你只是忘记分配内存。 :)