我是 c++
的新手,我在构造函数和类方面遇到了困难。所以,这是我的头文件:
#pragma once
#include <string>
using namespace std;
class test
{
private:
string name;
int number;
public:
test();
test(string i,int b);
};
这是cpp文件:
#include "test.h"
#include <string>
using namespace std;
test::test(){}
test::test(string i,int b){
this->name=i;
this->number=b;
}
现在,当我尝试调用
test t=new test("rrr",8);
我得到:
1 IntelliSense: no suitable constructor exists to convert from "test *" to "test"
那么,名称中包含 *
的类是怎么回事(例如,没有 .cpp 文件的类没有 asterix,所有其他类都有)?我做错了什么?
最佳答案
我想您有 Java/C# 背景。 t
这里不是引用类型,是值类型。 new
返回指向对象的指针。因此,您需要以下任何一项:
test t = test("rrr", 8);
test t("rrr", 8);
test *t = new test("rrr", 8);
如果您还不熟悉指针,那么绝对不要使用最后一个!但是理解指针的语义是相当关键的;我建议您阅读课本中的相关章节...
关于c++ - 不存在从 "test *"转换为 "test"的合适构造函数,构造函数,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15637556/