1

我正在为家庭作业编写一些课程,并且我希望我的课程成员函数不可能在 main 中被调用。如果是,我希望程序退出。我怎么知道我的成员函数何时被调用?至于类,每个对象代表一种颜色,格式为<100,200,215>。谢谢您的帮助!

class Color{

public:
    Color( unsigned red = 0, unsigned green = 0, unsigned blue = 0 );    //  ctor
    unsigned getRed() const;    //  accessor
    unsigned getGreen() const;    //  accessor
    unsigned getBlue() const;    //  accessor
    Color & setRed( unsigned red );    //  mutator
    Color & setGreen( unsigned green );    //  mutator
    Color & setBlue( unsigned blue );    //  mutator
    const Color & output() const;
private:
    unsigned myRed;
    unsigned myGreen;
    unsigned myBlue;
    static unsigned okColor(unsigned color);

}; //Class Color

int main(int argc, const char * argv[])
{

}


Color::Color( unsigned red, unsigned green, unsigned blue):
myRed(okColor(red)),myGreen(okColor(green)),myBlue(okColor(blue))
{
    //initialization list here...
}

//accessors
unsigned Color::getRed() const {return myRed;}
unsigned Color::getGreen() const {return myGreen;}
unsigned Color::getBlue() const {return myBlue;}

//mutators
Color & Color::setRed(unsigned red){
    myRed = okColor(red);
    return *this;
}

Color & Color::setGreen(unsigned green){
    myGreen = okColor(green);
    return *this;
}

Color & Color::setBlue(unsigned blue){
    myBlue = okColor(blue);
    return *this;
}

//output 
const Color & Color::output() const{

    cout << "<" << myRed << "," << myGreen << "," << myBlue << ">" << endl;
    return *this;
}

//checkers
unsigned Color::okColor(unsigned myColor){

    if (myColor > 255) {
        die("Color intensity is out of range!");
    }

    return myColor;
}

bool die(const string & msg){

    cerr << endl << "Fatal error: " << msg <<endl;
    exit(EXIT_FAILURE);
}

Color mixture( const Color & color0, const Color & color1, double weight){

    double color1Multiplier = 0;
    Color mixture;
    unsigned mixtureRed;
    unsigned mixtureBlue;
    unsigned mixtureGreen;

    color1Multiplier = 1 - weight;

    mixtureRed = (color0.getRed() * weight) + (color1.getRed() * color1Multiplier);
    mixtureBlue = (color0.getBlue() * weight) + (color1.getBlue() * color1Multiplier);
    mixtureGreen = (color0.getGreen() * weight) + (color1.getGreen() * color1Multiplier);

    mixture.setRed(mixtureRed);
    mixture.setBlue(mixtureBlue);
    mixture.setGreen(mixtureGreen);

    return mixture;
}
4

2 回答 2

2

防止从 main 调用您的类很简单。不要在main- 没有类 -> 无法调用成员函数(除非它们是静态的)中创建类。您还可以将#include类头文件移动到与main.

不幸的是,没有(琐碎和/或可移植的)方法来确定哪个函数调用了您的代码[特别是如果我们记住现代编译器经常移动代码,因此尽管您的代码是mixture从 main 调用的,编译器决定只是将其移入main,因为这使它更快,更小或编译器具有内联函数的任何其他目标]。

除此之外,没有办法阻止从任何有权访问该对象的函数调用函数。对于几乎每一个方面的功能,main都与其他功能没有什么不同。唯一的区别是main从 C++ 运行时库中调用。但是编译器并不真正关心您的函数是否被调用main,kerflunkfred.

于 2013-04-11T22:29:49.567 回答
0

如果您创建一个全局对象,它将在 之前初始化,并在退出main后销毁。main

您可以使用此事实来设置标志并按照您的意愿行事。

于 2013-04-11T22:30:43.783 回答