小编use*_*932的帖子

C++ 如何将字符串转换为字符

int main
{
  string data;
  data = "q";

  char myChoice;

  myChoice = data.c_str();
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用c_str(),但它不起作用。我如何转换stringchar

或者更确切地说我想问

int main()
{
  char myInput;
  // How to check user input is either a , b or c for char.
  cout << "Your Input ";
  cin >> myInput;
}
Run Code Online (Sandbox Code Playgroud)

因为string我可以使用getline(cin,mystringvariable),然后我使用 if-else 语句检查我的字符串变量。

但是炭呢?

c++

1
推荐指数
1
解决办法
2万
查看次数

C++将指针数组排序到对象

可能重复:
C++如何对数组变量进行排序

我有一个父类调用

Shape
Run Code Online (Sandbox Code Playgroud)

形状有2个孩子的电话

Square and Rectangle
Run Code Online (Sandbox Code Playgroud)

Shape类有一个变量调用区域,它是int类型

所以我创建了像Square,Rectangle这样的对象

int main()
{
    Shape *shaped[100];

    //then i did some adding of object..
    int areaValue;
    areaValue=1;

    shaped[0] = new Rectangle();
    shaped[0]->setArea(areaValue);

    areaValue=7;
    shaped[1] = new Square();
    shaped[1]->setArea(areaValue);

    areaValue=5;
    shaped[2] = new Square();
    shaped[2]->setArea(areaValue);

    shapeCounter = 3;


     sort(shaped, shaped + 3, sort_by_area());


    for (int i=0;i<shapeCounter;i++)
    {
        cout << shaped[i].getArea() << endl;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在例如Square.cpp

我这样做了

struct sort_by_area
{
    static bool operator()(Shape* x, Shape* y)
    {
        return x->getArea() < y->getArea();
    }
};
Run Code Online (Sandbox Code Playgroud)

上面的代码有效.并且可以按区域排序,但我的问题是,如果我不使用struct,我仍可以排序,因为如果我不使用struct,它会说sort_by_area未在范围内声明. …

c++ sorting class shapes

-1
推荐指数
1
解决办法
2489
查看次数

标签 统计

c++ ×2

class ×1

shapes ×1

sorting ×1