【问题标题】:Class and Object Microsoft Visual Studio Errors类和对象 Microsoft Visual Studio 错误
【发布时间】:2025-12-19 15:55:09
【问题描述】:

我必须用类和对象为学校制作一个 c++ 问题。

创建“Shaorma”类。

-会员资料:肉、大蒜、盐、胡椒;

-成员函数:隐式构造函数、参数

-构造函数,用于打印的函数

-screen,修改“garlic”成员类型的函数,

-返回肉,析构函数;

我使用 Microsoft Visual Studio 2013,但出现以下错误:

-Error 2 error LNK1120: 1 unresolved externals;

-错误 1 ​​错误 LNK2019:函数 _main 中引用的未解析外部符号“public: __thiscall shaorma::shaorma(void)”(??0shaorma@@QAE@XZ);

#include<iostream>
#include<conio.h>

using namespace std;

class shaorma
{
int salt, peper;
char meat[40];
char garlic[3];

public:
shaorma();
shaorma(int, int, char*, char*);
~shaorma();
void print();
void setgarlic(char*);
char* getmeat();
};

shaorma::shaorma(int s, int p, char *C, char *U)
{
salt = s;
peper = p;
strcpy_s(meat, C);
strcpy_s(garlic, U);
}

shaorma::~shaorma()
{
cout << "The destructor war called.";
}

void shaorma::print()
{
cout << "Shaorma has garlic:" << garlic;
cout << "," << salt << "salt";
cout << peper << "peper";
cout << "meat type:" << meat << endl;
}

void shaorma::setgarlic(char *U)
{
strcpy_s(garlic, U);
}

char* shaorma::getmeat()
{
return meat;
}

void main()
{
shaorma S1, S2(5, 4, "yes", "lamb");
S1.print();
S2.print();
S1.setgarlic("No");
S2.getmeat();
cout << "Meat is :" << S2.getmeat();
_getch();

}

【问题讨论】:

  • 默认构造函数的主体在哪里?
  • shaorma S1, S2(5, 4, "yes", "lamb"); 只有第二个接收这些参数。第一个是使用默认构造函数创建的。你的肉和大蒜参数是否正确?为什么不使用std::string,这样您就可以吃任何名称的肉,并将大蒜设置为bool

标签: c++ class object


【解决方案1】:

您声明了默认构造函数shaorma(),但忘记定义它

class shaorma
{
//...
public:
    shaorma();
    //...

这个构造函数用于main语句中对象S1的声明

shaorma S1, S2(5, 4, "yes", "lamb");

考虑到 main 应该有返回类型int

int main()

C++ 中的字符串文字也有常量字符数组的类型。当您在程序中使用字符串文字时,例如函数 setgarlic 应该声明为

void setgarlic( const char* );

【讨论】:

  • 它工作但现在我有另一个问题。L“缓冲区太小” && 0
  • @Andrei Gabriel 您将大蒜定义为只有 3 个字符,但尝试复制字符串文字“lamb”的至少 5 个字符
  • 成功了!为新手错误感到抱歉,但我刚开始,我试图理解所有错误和代码。非常感谢!