【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)

目录

9.1.4 设计立方体类

​编辑

9.1.5 成员函数在类的外部实现

9.1.6 类在其他源文件的实现步骤(实现类在不同文件的实现,后续引出构造函数) 

注意:类定义在同文件testclass.h中,而testclass.cpp是用来实现(声明)类的成员函数文件。


9.1.4 设计立方体类

现在如下图所示题目,设计一个立方体类,并且可以求出立方体的面积、体积,并最后判断是否相等,这里严格来说应该是设计一个长方体,立方体是长宽高都相等才是。

【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第1张图片

注意点:

【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第2张图片

【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第3张图片

完整代码:

#include 
#include 

class Cube{
private:
    int mLenth;//长
    int mWidth;//宽
    int mHeight;//高
public:
    void cubeInit(int ml,int mw,int mH){
        mLenth = ml;
        mWidth = mw;
        mHeight = mH;
    }
    //获取长宽高
    int getL(void){
        return mLenth;
    }
    int getW(void){
        return mWidth;
    }
    int getH(void){
        return mHeight;
    }
    //计算面积
    int getcubeS(){
        return (mLenth*mWidth + mLenth*mHeight + mWidth*mHeight)*2;
    }
    //计算体积
    int getcubeV(){
        return mLenth*mWidth*mHeight;
    }
    
    bool compareCube2(Cube &ob2){
        if(mLenth == ob2.getL() && mWidth == ob2.getW() && mHeight == ob2.getH()){
            return true;
        }
        return false;
    }
};


bool compareCube1(Cube &ob1,Cube &ob2)
{
    if(ob1.getL() == ob2.getL() && ob1.getH() == ob2.getH() && ob1.getW() == ob2.getW()){
        return true;
    }else{
        return false;
    }
}

void test04(){
    Cube ob1;
    ob1.cubeInit(10,20,30);
    cout << "面积:" <

9.1.5 成员函数在类的外部实现

【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第4张图片

9.1.6 类在其他源文件的实现步骤(实现类在不同文件的实现,后续引出构造函数) 

在Qt新建一个项目

【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第5张图片

 【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第6张图片

 【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第7张图片

 【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第8张图片

 这里可以直接选择在.cpp文件实现,注意,编写代码要严格区分大小写。

【带头学C++】----- 九、类和对象 ---- 9.1 类和对象的基本概念----(9.1.4---9.1.6)_第9张图片

注意:类定义在同文件testclass.h中,而testclass.cpp是用来实现(声明)类的成员函数文件。

代码:

testclass.h

#ifndef TESTCLASS_H
#define TESTCLASS_H


class TestClass
{
private:
    int mA;
public:
    void setA(int a);
    int getA();
};

#endif // TESTCLASS_H

testclass.cpp

#include "testclass.h"


void TestClass::setA(int a)
{
    mA = a;
}

int TestClass::getA()
{
    return mA;
}

main

#include "testclass.h"
void test05(){
    TestClass ob1;
    ob1.setA(111);
    cout << "ob1 = " <

你可能感兴趣的:(C++从基础到抗大旗,c++,开发语言,面试,c语言,算法)