【问题标题】:C++.Passing to functions.Syntax issueC++。传递给函数。语法问题
【发布时间】:2017-04-07 05:32:24
【问题描述】:

我正在通过自学来追求对 C++ 编程的兴趣。我现在正在研究一些基本的东西,目前在让我的课程说话/实例化时遇到问题?

我正在尝试让我的主 cpp 文件与头文件一起编译,并使用更有效的命令方法通过主文件调用一些类函数。

我被困住了,希望能得到一些帮助。我将包括这两个文件。我只是想通过调用函数从标头中获取返回值。

错误: main.cpp:6.21 错误:不能调用成员函数 'void myClass::setNumber(int) without object

代码在使用 main 编译时有效,因此我认为它与“范围解析运算符”有关。首先是main.cpp

#include <iostream>

#include "myClass.h"
using namespace std;
int main(){
myClass::setNumber(6);

{
 return number;
}
}

然后是我的头文件 myClass.h

// MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H


class myClass {

     private:

        int number;//declares the int 'number'
        float numberFloat;//declares the float 'numberFloat


    public:

        void setNumber(int x) {
            number = x;//wraps the argument "x" as  "number"
        }
        void setNumberFloat(float x) {
            numberFloat = x;
        }

        int getNumber() {//defines the function within the class. 

        number += 500;
            return number;
        }
        float getNumberFloat() {//defines the function
        numberFloat *= 1.07;
            return numberFloat;
    }

};

#endif

有什么帮助吗?

【问题讨论】:

标签: c++ scope resolution operator-keyword


【解决方案1】:

错误信息说明一切:

cannot call member function 'void myClass::setNumber(int)' without object

你需要先创建一个对象:

myClass obj;

然后调用该对象的类方法:

obj.setNumber(6);

值6 将分配给obj 变量的number 字段。

【讨论】:

    猜你喜欢
    • 2011-01-06
    • 1970-01-01
    • 2012-06-02
    • 2015-03-14
    • 1970-01-01
    • 2019-02-19
    • 2021-03-14
    • 2016-05-18
    • 2012-11-22
    相关资源
    最近更新 更多