c++ - 不存在从 "test *"转换为 "test"的合适构造函数,构造函数,

标签 c++ object pointers constructor instance

我是 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/

相关文章:

c++ - 我如何在 cinder 中使用 JUCE 库?

java - 从不同类的返回值检索对象时出现编译时错误。

javascript - 如何通过将用户输入与其键匹配来显示对象的值?

C: 当我尝试将我的结构传递到队列中时的核心转储

c++ - 阿格!反差挫败回调阴谋!想要更改虚拟返回类型

c++ - QProcess::execute ("clear") 问题

c++ - 无法在 uint64 上正确转换我的值?

JavaScript 对象和构造函数类型

c++ - 指针和引用 + 重载运算符

c++ - 在 shared_ptr 容器中查找元素?