[英]No variable member function declared in class?
我不斷收到此錯誤:
no 'int burrito::setName()' member function declared in class 'burrito'
我的目標是從其他類文件中調用函數
我的main.cpp:
#include <iostream>
#include "burrito.h"
using namespace std;
int main()
{
burrito a;
a.setName("Ammar T.");
return 0;
}
我的班級頭(burrito.h)
#ifndef BURRITO_H
#define BURRITO_H
class burrito
{
public:
burrito();
};
#endif // BURRITO_H
我的課程文件(burrito.cpp):
#include "burrito.h"
#include <iostream>
using namespace std;
burrito::setName()
{
public:
void setName(string x){
name = x;
};
burrito::getName(){
string getName(){
return name;
};
}
burrito::variables(string name){
string name;
};
private:
string name;
};
您的代碼一團糟。 您需要在頭文件中編寫函數原型,並在cpp文件中編寫函數定義。 您缺少一些基本的編碼結構。 參見下文,了解這種編碼模式:
此代碼應該可以正常工作並享受墨西哥卷餅!
主要():
#include <iostream>
#include "Header.h"
int main()
{
burrito a;
a.setName("Ammar T.");
std::cout << a.getName() << "\n";
getchar();
return 0;
}
CPP文件:
#include "Header.h"
#include <string>
void burrito::setName(std::string x) { this->name = x; }
std::string burrito::getName() { return this->name; }
頭文件:
#include <string>
class burrito
{
private:
std::string name;
public:
void setName(std::string);
std::string getName();
//variables(string name) {string name;} // What do you mean by this??
};
你可憐的小卷餅很困惑。 墨西哥卷餅無濟於事。
您可能希望將墨西哥卷餅聲明為:
class Burrito
{
public:
Burrito();
void set_name(const std::string& new_name);
std::string get_name() const;
private:
std::string name;
};
這些方法可以在源文件中定義為:
void
Burrito::set_name(const std::string& new_name)
{
name = new_name;
}
std::string
Burrito::get_name() const
{
return name;
}
頭文件僅具有該類的構造函數。 成員功能
setName(string) and getName()
沒有在頭文件中聲明,這就是為什么您得到錯誤。 另外,您需要指定函數的返回類型。
一種方法是
//Header
//burrito.h
class burrito{
private:
string burrito_name;
public:
burrito();
string getName();
void setName(string);
}
//burrito.cpp
#include "burrito.h"
#include <iostream>
using namespace std;
string burrito::getName()
{
return burrito_name;
}
void burrito::setName(string bname)
{
bname =burrito_name;
}
這是C ++中的類的簡單示例,
將此保存在burrito.cpp
文件中,然后編譯並運行它:
#include <iostream>
#include <string>
using namespace std;
class burrito {
public:
void setName(string s);
string getName();
private:
string name;
};
void burrito::setName(string s) {
name = s;
}
string burrito::getName() {
return name;
}
int main() {
burrito a;
a.setName("Ammar T.");
std::cout << a.getName() << "\n";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.