无法创建一个类的多个实例

Cannot create multiple instances of a class?

本文关键字:实例 一个 创建      更新时间:2023-10-16

我的问题是,我想为不同的升级创建升级类的多个实例。也许是因为我习惯了java,但我不能只键入Source first("first"), second("second");,因为如果我这样做并调用first.getName(),例如,我会得到"second"。我做了一个示例文件,我只写了我正在努力解决的问题,所以你不必试图理解我混乱的代码。

Source.cpp:我想要这个类的多个实例。

#include "Source.h"
std::string name;
Source::Source()
{
}
Source::Source(std::string nameToSet) 
{
name = nameToSet;
}
std::string Source::getName()
{
return name;

Source.h

#pragma once
#include <string>
class Source {
public:
Source();
Source(std::string namel);
std::string getName();
};

测试.cpp

#include "Source.h"
#include "iostream"
Source first("first"), second("second");
int main()
{
std::cout << first.getName() << std::endl;
}

输出:秒

测试.h

#pragma once
#include <string>

问题出在这行:

std::string name;

这声明了一个名为name的全局字符串。此变量未与任何Source实例关联。相反,您需要在Source类中声明一个字段:

class Source {
public:
Source();
Source(std::string namel);
std::string getName();
// Add these two lines
private:
std::string name;
};

这将为每个Source提供一个name。我建议您研究类字段以及publicprivate访问之间的差异。

在头文件中添加std::string名称,如下所示:

#pragma once
#include <string>
class Source {
private:
std::string name;
public:
Source();
Source(std::string namel);
std::string getName();
};

这样,每次调用构造函数时,"name"都会被初始化为一个值,该值引用您的特定实例(第一个、第二个等(。