1 c++-cli
-----你好,世界2.cpp -----
// Hello, World 2.cpp : main project file.
#include "stdafx.h"
#include "hello.h"
#include <string>
using namespace System;
using namespace std;
int main(array<System::String ^> ^args)
{
hello hi = new hello("Bob", "Blacksmith");
Console::WriteLine(L"Hello, " + hi.getName + "!");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
----- hello.h -----
#include <string>
using namespace std;
#ifndef HELLO_H
#define HELLO_H
class hello
{
private:
string _fname;
string _lname;
//hello() { } // private default constructor
public:
hello(string fname, string lname);
void SetName(string fname, string lname);
string GetName();
};
#endif
Run Code Online (Sandbox Code Playgroud)
----- hello.cpp -----
#include "stdafx.h"
#include "hello.h"
#include <string>
using namespace std;
hello::hello(string fname, string lname)
{
SetName(fname, lname);
}
void hello::SetName(string fname, string lname)
{
_fname = fname;
_lname = lname;
}
string hello::getName()
{
return _fname + _lname;
}
Run Code Online (Sandbox Code Playgroud)
-----错误-----
错误消息可以准确地告诉您问题的位置和问题,尽管它们起初可能有点令人生畏.也许我可以帮助他们揭开神秘面纱:
你好,World 2.cpp(12):错误C2440:'初始化':无法从'hello*'转换为'hello'
这意味着在Hello,World 2.cpp中的第12行,你试图在其中放置一个指针hello(返回new),hi这不是指针类型.由于您不需要动态分配的对象,只需删除即可new.
在需要动态分配对象的情况下,您可以将hi变量更改为hello *并添加相应的对象delete.
你好,World 2.cpp(13):错误C2039:'getName':不是'hello'的成员
C++区分大小写.在一个文件中,你有GetName,在其他的你有getName.选一个.
hello.cpp(19):错误C2065:'_ fname':未声明的标识符hello.cpp(19):错误C2065:'_ lname':未声明的标识符
hello.cpp的第19行是小写的定义getName.由于getName未在类中声明(请参阅上一个错误),编译器不知道是什么_fname或是什么_lname.一旦原始问题得到解决,这些错误就会消失.
编辑
请参阅@ Sergey的答案,了解其他一些需要修复的事项.