假设我有两个名为Computer.h和Software.h的头文件两者都是在分开的文件Computer.cpp和Software.cpp上实现的,我担心的是在计算机中声明软件。
计算机.h
#ifndef _COMPUTER_H
#define _COMPUTER_H
#include "Software.h"
class Computer{
private:
std::string computerName;
int ramSize;
Software computerSoftware;
public:
Computer();
Computer(std::string name, int size);
int GetRamSize();
std::string GetComputerName();
};
#endif
软件.h
#ifndef _SOFTWARE_H
#define _SOFTWARE_H
class Software{
private:
std::string softwareName;
double softwarePrice;
public:
Software();
Software(std::string name, double price);
double GetPrice();
std::string GetSoftwareName();
};
#endif
计算机.cpp
#include <string>
#include <iostream>
#include "Computer.h"
using namespace std;
Computer::Computer(string name, int size){
computerName = name;
ramSize = size;
}
int Computer::GetRamSize(){
return ramSize;
}
string Computer::GetComputerName(){
return computerName;
}
软件.cpp
#include <string>
#include <iostream>
#include "Software.h"
using namespace std;
Software::Software(string name, double price){
softwareName = name;
softwarePrice = price;
}
double Software::GetPrice(){
return softwarePrice;
}
string Software::GetSoftwareName(){
return softwareName;
}
然而,它在我的visual c++2010 express上交付了构建错误:
Computer.obj:错误LNK2019:未解析的外部符号"public:__thiscall软件::软件(无效)"(??0软件@@QAE@XZ)在函数"public:__thiscall Computer::Computer(类std::basic_string,类std::allocater>,int)"(??0计算机@@QAE@V$basic_string@DU$char_traits@D@std@@V$allocator@D@2@@std@@H@Z)1> C:\Users\farissyariati\documents\visual studio
2010\Projects\CppConsoleApps\Debug\CpconsoleApps.exe:致命错误LNK1120:1个未解析的外部
此函数
Computer::Computer(string name, int size){
computerName = name;
ramSize = size;
}
相当于:
Computer::Computer(string name, int size) : computerName(), computerSoftware() {
computerName = name;
ramSize = size;
}
CCD_ 1和CCD_。由于您没有实现Software
的默认构造函数,因此您遇到了链接器错误。
在Software.cpp
中实现Software::Software()
,一切正常。
Software::Software() : softwareName(), softwarePrice(0.0) {
}