类中未声明变量成员函数

No variable member function declared in class?

本文关键字:成员 函数 变量 未声明      更新时间:2023-10-16

可以向我解释为什么我的代码不起作用,以及如何修复它,谢谢:)

我一直收到这个错误:

no 'int burrito::setName()' member function declared in class 'burrito'

我的目标是从不同的类文件中调用一个函数

我的主.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文件中编写功能定义。您缺少一些基本的编码结构。请参阅下面的内容并学习这种编码模式:

这个代码应该可以工作并享受墨西哥卷饼!

main():

#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;
}