c ++查找字符串_C ++类和对象| 查找输出程序| 套装3

c ++查找字符串

Program 1:

程序1:

#include <iostream>
using namespace std;

class Sample {
    int X;

public:
    void set(int x)
    {
        X = x;
    }
    void print()
    {
        cout << X << " ";
    }

} A, B;

int main()
{
    A.set(10);
    B.set(20);

    A.print();
    B.print();

    return 0;
}

Output:

输出:

10 20

Explanation:

说明:

In the above program, we created class Sample and two objects A and B using before semicolon at the end of the class.

在上面的程序中,我们创建了Sample类,并在类末尾使用分号前的两个对象AB。

In the main() function, we call set() and print() function, then it will print "10 20" on the console screen.

main()函数中,我们调用set()print()函数,然后它将在控制台屏幕上打印“ 10 20”

Program 2:

程式2:

#include <iostream>
using namespace std;

const class Sample {
    int X;

public:
    void set(int x)
    {
        X = x;
    }
    void print()
    {
        cout << X << " ";
    }
};

int main()
{
    Sample A;
    Sample B;

    A.set(10);
    B.set(20);

    A.print();
    B.print();

    return 0;
}

Output:

输出:

main.cpp:4:1: error: ‘const’ can only be specified for objects and functions
 const class Sample {
 ^~~~~

Explanation:

说明:

The above program will generate an error because we cannot use the const keyword with class declaration. The const keyword can be used with data members and member functions of the class.

上面的程序将产生错误,因为我们不能在类声明中使用const关键字const关键字可与类的数据成员和成员函数一起使用。

Program 3:

程式3:

#include <iostream>
using namespace std;

class Sample {
    int X;

public:
    void set(int x);
    void print();
};

void Sample : set(int x)
{
    X = x;
}

void Sample : print()
{
    cout << X << " ";
}

int main()
{
    Sample A;
    Sample B;

    A.set(10);
    B.set(20);

    A.print();
    B.print();

    return 0;
}

Output:

输出:

main.cpp:12:13: error: found ‘:’ in nested-name-specifier, expected ‘::’
 void Sample : set(int x)
             ^
main.cpp:17:13: error: found ‘:’ in nested-name-specifier, expected ‘::’
 void Sample : print()
             ^

Explanation:

说明:

The above program will generate errors because in the above program we declare member function inside the class and defined outside the class. But we use the colon operator instead of scope resolution operator ("::" ).

上面的程序将产生错误,因为在上面的程序中,我们在类内部声明成员函数 ,并在类外部定义成员函数 。 但是我们使用冒号运算符而不是范围解析运算符(“ ::”)

Recommended posts

推荐的帖子

翻译自: https://www.includehelp.com/cpp-tutorial/class-and-objects-find-output-programs-set-3.aspx

c ++查找字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值